package com.hsqyz.common.utils.id;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;

/**
 * id生成工具
 */
@Slf4j
@Component
public class GenerateIdUtil {

    private static final long datacenterId = 1;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private static long workId;
    private static final Snowflake snowflake = IdUtil.getSnowflake(workId, datacenterId);

    public static synchronized long getNormalGenerateId() {
        return snowflake.nextId();
    }

    @PostConstruct
    public static void init() {
        workId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
    }

    public static void main(String[] args) {
        HashSet<Long> set = new HashSet<>();
        for (int i = 0; i < 999999; i++) {
            long normalGenerateId = getNormalGenerateId();
            set.add(normalGenerateId);
        }
        System.out.println(set.size());
    }

}
